
#
# Author : itech
# 

import os
import Common

def runCommand(cmd):
  result,stdout,stderr = Common.runCommandWithOutput(cmd)
  if not stderr == '' : print stderr
  #if not stdout == '' : print stdout
  if not result == 0 or not stderr == '' :
    print 'Failed for the command: ' + cmd
    return False
  else:
    print 'Successful for the command: ' + cmd
    return True
  
def SubstDriverToPath(Driver, path):
  substcmd = "subst" + " " + Driver + " " + path
  return runCommand(substcmd)
  
def UnSubstDriverToPath(Driver):
  unsubstcmd = "subst" + " " +Driver + " " + "/d"
  return runCommand(unsubstcmd)
  
def NetuseDriverToPath(Driver, path):
  netusecmd = "net use" + " " + Driver + " " + path
  return runCommand(netusecmd)
  
def UnNetuseDriverToPath(Driver):
  unnetusecmd = "net use" + " " + Driver + " " + "/del"
  return runCommand(unnetusecmd)
    
def SubstDriverToPathF(Driver, path):
  UnSubstDriverToPath(Driver)
  UnNetuseDriverToPath(Driver)  
  return SubstDriverToPath(Driver, path)
   
def NetuseDriverToPathF(Driver, path):
  UnSubstDriverToPath(Driver)
  UnNetuseDriverToPath(Driver)
  return NetuseDriverToPath(Driver, path)
  
def AutoSubstorNetuse(path):
  successful = False
  
  if(not os.path.isdir(path) or not os.path.exists(path)):
    print("path is not existed or is not a directory")
    return successful
  
  netuse = False
  if(path.startswith("\\\\")):
    netuse = True
  
  usedDriver = ""
  for Driver in "ZYXWVUTSRQPONMLKJIHGFEDCBA":
    fullDriver = Driver + ":"
    if(netuse):      
      if(NetuseDriverToPath(fullDriver, path)):
        usedDriver = fullDriver
        break
    else:      
      if(SubstDriverToPath(fullDriver,path)):
        usedDriver = fullDriver
        break
  if(not usedDriver == ""):
    successful = True
  else:
    print 'no driver can be used.'
    
  return successful, usedDriver
  
def Usage():
  print '''
  Usage:
  python SubstOrNetuse.py SubstDriverToPathF driver path
  python SubstOrNetuse.py NetuseDriverToPathF driver networkpath
  python SubstOrNetuse.py AutoSubstorNetuse pathornetworkpath
  Examples:
  python SubstOrNetuse.py SubstDriverToPathF Y: C:\\test
  python SubstOrNetuse.py NetuseDriverToPathF X: \\\\remotemachinenameorip\\shared
  python SubstOrNetuse.py AutoSubstorNetuse c:\\test
  python SubstOrNetuse.py AutoSubstorNetuse \\\\remotemachinenameorip\\shared
  '''
  
def Main(argv):
  if len(argv) == 3 and str.lower(argv[0]) == 'substdrivertopathf':
    SubstDriverToPathF(argv[1],argv[2])
  elif len(argv) == 3 and str.lower(argv[0]) == 'netusedrivertopathf':
    NetuseDriverToPathF(argv[1],argv[2])
  elif len(argv) == 2 and str.lower(argv[0]) == 'autosubstornetuse':
    AutoSubstorNetuse(argv[1])
  else:
    Usage()
  
if __name__ == "__main__" :
    import sys
    Main(sys.argv[1:])
